const express = require('express');
const router = express.Router();
const Share = require('../models/share');
const multer = require('multer');
const path = require('path');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/uploads/products/share')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, uniqueSuffix + path.extname(file.originalname))
  }
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只能上传图片文件！'));
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

// 创建分享
router.post('/create', async (req, res) => {
  try {
    const shareData = req.body;
    const share = new Share(shareData);
    await share.save();
    res.status(200).json({
      success: true,
      data: share
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 获取分享列表
router.get('/list', async (req, res) => {
  try {
    const { platform, status, page = 1, limit = 10 } = req.query;
    const query = {};
    
    if (platform) query.platform = platform;
    if (status !== undefined) query.status = status;

    const shares = await Share.find(query)
      .sort({ shareTime: -1 })
      .skip((page - 1) * limit)
      .limit(Number(limit));

    const total = await Share.countDocuments(query);

    res.status(200).json({
      success: true,
      data: {
        list: shares,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 更新分享状态
router.put('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    const share = await Share.findByIdAndUpdate(
      id,
      { status },
      { new: true }
    );

    if (!share) {
      return res.status(404).json({
        code:500,
        message: '分享不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: share
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 删除分享
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const share = await Share.findByIdAndDelete(id);

    if (!share) {
      return res.status(404).json({
        code:500,
        message: '分享不存在'
      });
    }

    res.status(200).json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 单个文件上传
router.post('/upload/single', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      throw new Error('请选择要上传的文件');
    }
    
    const fileUrl = `/uploads/products/share/${req.file.filename}`;
    
    res.status(200).json({
      success: true,
      data: {
        url: fileUrl
      }
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

module.exports = router; 